<template>
    <div class="authority">
        <div class="gva-search-box">
            <el-form ref="searchForm" :inline="true">
                <el-form-item label="人员身份">
                    <el-select v-model="searchInfo.identity" placeholder="请选择">
                        <el-option v-for="item in identitys" :key="item.id" :label="item.name" :value="item.id" />
                    </el-select>
                </el-form-item>
                <el-form-item label="部门">
                    <el-select v-model="searchInfo.departId" placeholder="请选择">
                        <el-option v-for="item in departments" :key="item.id" :label="item.departName"
                            :value="item.id" />
                    </el-select>
                </el-form-item>
                <el-form-item label="姓名">
                    <el-input v-model="searchInfo.name" placeholder="请输入" />
                </el-form-item>
                <el-form-item label="房名/房号">
                    <el-input v-model="searchInfo.roomNo" placeholder="请输入" />
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" icon="search" @click="onSubmit">
                        查询
                    </el-button>
                    <el-button icon="refresh" @click="onReset">重置</el-button>
                </el-form-item>
            </el-form>
        </div>
        <div class="gva-table-box unit">
            <div class="gva-btn-list">
                <el-button type="primary" icon="plus" @click="addUnit">新增人员</el-button>
                <!-- <el-button type="danger" icon="delete" @click="batchDel"
                    :disabled="useRoomIds.length == 0">批量删除</el-button> -->
            </div>
            <el-table :data="tableData" row-key="id">
                <el-table-column type="index" label="序号" width="100" />
                <el-table-column align="left" label="部门" prop="departName"></el-table-column>
                <el-table-column align="left" label="姓名" prop="name"></el-table-column>
                <el-table-column align="left" label="职级" prop="rank"></el-table-column>
                <el-table-column align="left" label="人员身份">
                    <template #default="scope">
                        {{ identitys[scope.row.identity - 1].name }}
                    </template>
                </el-table-column>
                <el-table-column align="left" label="房名/房号" prop="roomNo"></el-table-column>
                <el-table-column align="left" label="房间面积" prop="roomArea"></el-table-column>
                <el-table-column align="left" fixed="right" label="操作" min-width="160">
                    <template #default="scope">
                        <el-button type="primary" link icon="edit" @click="editUnit(scope.row)">
                            编辑
                        </el-button>
                        <el-button type="danger" link icon="delete" @click="delUnit(scope.row)">
                            删除
                        </el-button>
                    </template>
                </el-table-column>
            </el-table>
            <div class="gva-pagination">
                <el-pagination v-model:current-page="page" :page-size="pageSize" :total="total"
                    layout="prev, pager, next" @current-change="handleCurrentChange" />
            </div>
        </div>
        <el-drawer v-model="dialogFormVisible" :size="1000" :before-close="handleClose" :show-close="false">
            <template #header>
                <div class="flex justify-between items-center">
                    <span class="text-lg">{{ dialogTitle }}</span>
                    <div>
                        <el-button @click="closeDialog">取消</el-button>
                        <el-button type="primary" @click="enterDialog">确定</el-button>
                    </div>
                </div>
            </template>
            <el-form v-if="dialogFormVisible" ref="yyglForm" label-width="150" :model="form" :rules="rules">
                <el-form-item label="姓名" prop="name">
                    <el-input v-model="form.name" placeholder="请输入" style="width: 360px;" />
                    <span style="margin-left: 4px;color: #FF473E;">注:请输入真实姓名,请确保数据准确</span>
                </el-form-item>
                <el-form-item label="职务" prop="job">
                    <el-input v-model="form.job" placeholder="请输入" style="width: 360px;" />
                    <span style="margin-left: 4px;color: #FF473E;">注:请输入真实职务,请确保数据准确</span>
                </el-form-item>
                <el-form-item label="在职情况" prop="onJobState">
                    <el-radio-group v-model="form.onJobState" class="ml-4">
                        <el-radio :value="1" size="large">在职</el-radio>
                        <el-radio :value="2" size="large">退休</el-radio>
                        <el-radio :value="3" size="large">离休</el-radio>
                        <el-radio :value="4" size="large">其他</el-radio>
                    </el-radio-group>
                </el-form-item>
                <el-form-item label="人员身份" prop="identity">
                    <el-radio-group v-model="form.identity" class="ml-4">
                        <el-radio v-for="item in identitys" :value="item.id" size="large">{{ item.name }}</el-radio>
                    </el-radio-group>
                </el-form-item>
                <el-form-item label="所属部门" prop="departId">
                    <el-select v-model="form.departId" placeholder="请选择" style="width: 360px;">
                        <el-option v-for="item in departments" :key="item.id" :label="item.departName"
                            :value="item.id" />
                    </el-select>
                    <span style="margin-left: 4px;color: #FF473E;">注:若无所属部门信息，请到组织结构(部门)内添加</span>
                </el-form-item>
                <el-form-item label="职级" prop="rank">
                    <el-select v-model="form.rank" placeholder="请选择" style="width: 360px;">
                        <el-option v-for="item in zjList" :key="item.rank" :label="item.rank" :value="item.rank" />
                    </el-select>
                </el-form-item>
                <el-form-item label="领导" prop="leader">
                    <el-radio-group v-model="form.leader" class="ml-4">
                        <el-radio :value="1" size="large">是</el-radio>
                        <el-radio :value="2" size="large">否</el-radio>
                    </el-radio-group>
                </el-form-item>
                <el-form-item label="所属办公楼" prop="buildingId">
                    <el-select v-model="form.buildingId" placeholder="请选择" style="width: 360px;" @change="changeBuild">
                        <el-option v-for="item in ldTabs" :key="item.buildingId" :label="item.name"
                            :value="item.buildingId" />
                    </el-select>
                    <span style="margin-left: 4px;color: #FF473E;">注:若无所属办公楼信息，请到办公楼信息内添加</span>
                </el-form-item>
                <el-form-item label="所属楼层" prop="floorId">
                    <el-select v-model="form.floorId" placeholder="请选择" style="width: 360px;" @change="changeFloor">
                        <el-option v-for="item in lcList" :key="item.id" :label="item.floor" :value="item.id" />
                    </el-select>
                </el-form-item>
                <el-form-item label="房间名" prop="roomId">
                    <el-select v-model="form.roomId" placeholder="请选择" style="width: 360px;">
                        <el-option v-for="item in fjList" :key="item.id" :label="item.roomNo" :value="item.id" />
                    </el-select>
                </el-form-item>
                <el-form-item label="卫生间面积" prop="toiletArea">
                    <el-input v-model="form.toiletArea" placeholder="请输入" style="width: 360px;" />
                    <span style="margin-left: 4px;">平方米</span>
                </el-form-item>
            </el-form>
        </el-drawer>
    </div>
</template>
<script setup>
import {
    getYfList,
    deleteYf,
    createYf,
    updateYf,
    batchDeleteYf,
    getZjList
} from '@/api/xitongpeizhi'
import {
    unitDepartment,
    unitBuilding,
    unitRoom,
    addEmployee,
    editEmployee,
    unitBaseInfo,
    unitEmployee,
    deleteEmployee
} from '@/api/unit'
import { reactive, ref, onMounted } from 'vue'
import { useAppStore } from "@/pinia";
import { useUserStore } from '@/pinia/modules/user'
import { ElMessage, ElMessageBox, useFormItem } from 'element-plus'
import { identitys } from '@/utils/constant'

// 通过该函数，可以获取组件当前所在的表单项formItem
const { formItem } = useFormItem()

defineOptions({
    name: 'Yygl'
})
const appStore = useAppStore()
const form = ref({
    buildingId: '',
    departId: '',
    floorId: '',
    identity: 1,
    job: '',
    leader: 1,
    name: '',
    onJobState: 1,
    rank: '',
    roomArea: '',
    roomId: '',
    toiletArea: '',
    unitId: '',
    employeeId: ''
})
const searchInfo = ref({
    departId: '',
    identity: '',
    name: '',
    roomNo: '',
    unitId:JSON.parse(localStorage.getItem('userInfo')).unitId
})

const ldTabs = ref([])
const lcList = ref([])
const fjList = ref([])
const zjList = ref([])
const zjObj = {
    '省级正职': 54,
    '省级副职': 42,
    '正厅(局)级': 30,
    '副厅(局)级': 24,
    '正处级': 18,
    '副处级': 12,
    '处级以下': 9,
    '市级正职': 42,
    '市级副职': 30,
    '正局(处)级': 24,
    '副局(处)级': 18,
    '局(处)级以下': 9,
    '县级正职': 30,
    '县级副职': 24,
    '正科级': 18,
    '副科级': 12,
    '科级以下': 9,
    '乡级正职': 0,
    '乡级副职': 0,
    '乡级以下': 0,
}
function getUnitBuilding() {
    unitBuilding().then(res => {
        if (res.result) {
            ldTabs.value = res.result
        }
    })
    Promise.all([unitBaseInfo(), getZjList()]).then(res => {
        let realName = res[1].result.data.find(item => item.id == res[0].result.rank).realName
        let zjArr = realName.split('|')
        for (const key in zjObj) {
            if (zjArr.includes(key)) {
                zjList.value.push({
                    rank: key,
                    area: String(zjObj[key]),
                    numbers: 0,
                    type: 1
                })
            }
        }
    })
}
function changeBuild(val) {
    console.log(ldTabs.value,val,'bnb')
    let obj = ldTabs.value.find(item => item.buildingId == val)
    console.log(obj,'obj')
    lcList.value = obj.floors
}
function changeFloor(val) {
    let params = {
        buildingId: form.value.buildingId,
        floorId: form.value.floorId,
        unitId: searchInfo.value.unitId
    }
    form.value.roomId = ''
    unitRoom(params).then(res => {
        fjList.value = res.result
    })
}
const userStore = useUserStore()
const headerOdj = ref({ token: userStore.token })
const adminUrl = ref('')
adminUrl.value = import.meta.env.VITE_BASE_PATH + '/file/upload'
const page = ref(1)
const total = ref(0)
const pageSize = ref(10)
const dialogFormVisible = ref(false)

const rules = reactive({
    name: [{ required: true, message: '请输入用房类型名称', trigger: 'blur' }],
    onJobState: [{ required: true, message: '请选择在职情况', trigger: 'change' }],
    job: [{ required: true, message: '请输入职务', trigger: 'blur' }],
    identity: [{ required: true, message: '请选择人员身份', trigger: 'change' }],
    departId: [{ required: true, message: '请选择所属部门', trigger: 'change' }],
    rank: [{ required: true, message: '请选择职级', trigger: 'change' }],
    leader: [{ required: true, message: '请选择职级', trigger: 'change' }],
    buildingId: [{ required: true, message: '请选择所属办公楼', trigger: 'change' }],
    floorId: [{ required: true, message: '请选择所属楼层', trigger: 'change' }],
    roomId: [{ required: true, message: '请选择房间名', trigger: 'change' }],
})

const yyglForm = ref(null)

const initForm = () => {
    yyglForm.value.resetFields()
    form.value = {
        buildingId: '',
        departId: '',
        floorId: '',
        identity: 1,
        job: '',
        leader: 1,
        name: '',
        onJobState: 1,
        rank: '',
        roomArea: '',
        roomId: '',
        toiletArea: '',
        unitId: JSON.parse(localStorage.getItem('userInfo')).unitId,
        employeeId: ''
    }
}

const isEdit = ref(false)
const dialogTitle = ref('新增人员')
const addUnit = () => {
    dialogTitle.value = '新增人员'
    isEdit.value = false
    dialogFormVisible.value = true
}
const closeDialog = () => {
    initForm()
    dialogFormVisible.value = false
}

const handleClose = (done) => {
    initForm()
    done()
}
const handleUserClose = (done) => {
    initUserForm()
    done()
}
const handleCurrentChange = (val) => {
    page.value = val
    getTableData()
}
const tableData = ref([])
// 查询
const getTableData = async () => {
    const res = await unitEmployee({
        pageNumber: page.value,
        pageSize: pageSize.value,
        ...searchInfo.value
    })
    if (res.code == 200) {
        tableData.value = res.result.data
        total.value = res.result.total
    }
}
const departments = ref([])
function getDeptData() {
    unitDepartment().then(res => {
        departments.value = res.result
    })
}

const typeList = ref([{ name: '内部URL', id: 1 }, { name: '外部URL', id: 2 }])
const roleList = ref([])
onMounted(() => {
    if (localStorage.getItem('userInfo')) {
        form.value.unitId = JSON.parse(localStorage.getItem('userInfo')).unitId
        searchInfo.value.unitId = JSON.parse(localStorage.getItem('userInfo')).unitId
    }
    getDeptData()
    getUnitBuilding()
    getTableData()
})

const enterDialog = async () => {
    yyglForm.value.validate(async (valid) => {
        if (valid) {
            let res
            if (isEdit.value) {
                res = await editEmployee(form.value)
            } else {
                res = await addEmployee(form.value)
            }
            if (res.code == 200) {
                ElMessage({
                    type: 'success',
                    message: isEdit.value ? '编辑成功' : '添加成功!'
                })
                getTableData()
            }
            initForm()
            dialogFormVisible.value = false
        }
    })
}

const delUnit = (row) => {
    ElMessageBox.confirm(
        '确认删除?',
        '提示',
        {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
        }
    ).then(async () => {
        const res = await deleteEmployee(row.id)
        if (res.code === 200) {
            ElMessage({
                type: 'success',
                message: '删除成功!'
            })
            getTableData()
        }
    }).catch(() => {
        ElMessage({
            type: 'info',
            message: '已取消删除'
        })
    })
}

const editUnit = async (row) => {
    isEdit.value = true
    dialogTitle.value = '编辑人员'
    form.value = JSON.parse(JSON.stringify(row))
    form.value.employeeId = form.value.id
    dialogFormVisible.value = true
}
const statusChange = (id, val) => {
    changeStatus(id).then(res => {
        ElMessage({
            type: 'success',
            message: '状态修改成功!'
        })
        getTableData()
    })
}
const onSubmit = () => {
    page.value = 1
    getTableData()
}

const onReset = () => {
    page.value = 1
    searchInfo.value = {
        departId: '',
        identity: '',
        name: '',
        roomNo: '',
        unitId: JSON.parse(localStorage.getItem('userInfo')).unitId
    }
    getTableData()
}

const fileList = ref([])
const handleRemove = (file) => {
    fileList.value = []
    form.value.ico = ''
}
const uploadSuccess = (res) => {
    if (res.code != 200) {
        ElMessage({
            type: 'error',
            message: '上传失败' + res.msg
        })
        fileList.value.pop()
        return
    }
    form.value.ico = res.result
    yyglForm.value.validateField('ico')
}

const batchDel = () => {
    ElMessageBox.confirm(
        '确认删除?',
        '提示',
        {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
        }
    ).then(async () => {
        const res = await batchDeleteYf({ useRoomIds: useRoomIds.value })
        if (res.code === 200) {
            ElMessage({
                type: 'success',
                message: '删除成功!'
            })
            getTableData()
        }
    }).catch(() => {
        ElMessage({
            type: 'info',
            message: '已取消删除'
        })
    })
}
</script>

<style lang="scss" scoped>
.flex {
    .area {
        flex: 2;
        background-color: #fff;
        margin: 0.5rem 20px 0.5rem 0;
    }

    .unit {
        flex: 4;
    }
}

.ant-alert-info {
    display: flex;
    justify-content: end;
    align-items: center;
    background-color: #e6f7ff;
    border: 1px solid #91d5ff;
    color: #1890ff;
    padding: 5px;

    .anticon {
        display: flex;
        align-items: center;
        cursor: pointer;
    }
}

.pop-content {
    .pop-title {
        font-weight: bold;
        padding-bottom: 4px;
        border-bottom: 1px solid rgba(5, 5, 5, 0.06);
    }

    .el-checkbox-group {
        font-size: 0;
        line-height: 0;
        display: flex;
        flex-wrap: wrap;
    }
}
</style>